﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using WebApiClientCore;
using WebApiClientCore.Attributes;
using XUCore.Extensions;
using XUCore.NetCore;

namespace XUCore.WeChat.Enterprise.Apis
{
    public class EnterpriseWeChatAccessTokenApiFilter : ApiFilterAttribute
    {
        public override async Task OnRequestAsync(ApiRequestContext context)
        {
            var suiteId = Web.Request.Headers["SuiteId"].SafeString();
            var corpId = Web.Request.Headers["CorpId"].SafeString();
            var agentId = Web.Request.Headers["AgentId"].SafeString().ToInt();

            var tokenManager = context.HttpContext.ServiceProvider.GetRequiredService<IEnterpriseWeChatTokenManager>();
            string accessToken = await tokenManager.GetAccessTokenAsync(suiteId, corpId, agentId);
            context.HttpContext.RequestMessage.AddUrlQuery("access_token", accessToken);

            if (context.HttpContext.RequestMessage.Content != null)
            {
                var data = await context.HttpContext.RequestMessage.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(data))
                {
                    var logger = context.HttpContext.ServiceProvider.GetRequiredService<ILogger<EnterpriseWeChatAccessTokenApiFilter>>();
                    logger.LogInformation(data);
                }
            }
        }

        public override async Task OnResponseAsync(ApiResponseContext context)
        {
            if (context.HttpContext.ResponseMessage.Content != null && context.HttpContext.ResponseMessage.IsSuccessStatusCode)
            {
                var data = await context.HttpContext.ResponseMessage.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(data))
                {
                    var logger = context.HttpContext.ServiceProvider.GetRequiredService<ILogger<EnterpriseWeChatAccessTokenApiFilter>>();
                    logger.LogInformation(data);
                }
            }
        }
    }
}
